<template lang="pug">
#pano(
  @mousedown='handleDown',
  @mousemove='handleMove',
  @mouseup='handelUp',
  @touchstart='handleDown',
  @touchmove='handleMove',
  @touchend='handelUp'
)
</template>

<script>
import {
  handleScreenShotsDown,
  handleScreenShotsMove,
  handleScreenShotsEnd,
} from '@/utils/scene'
// import { handleSystemMenu } from '@/utils/menu'
import Hammer from 'hammerjs'
import autoSwitchSceneMixin from '@/mixins/switch-scene'
import CONFIG from '@/config'
import { mapGetters } from 'vuex'
export default {
  mixins: [autoSwitchSceneMixin],
  data() {
    return {
      isScreenShots: true,
      isHideAll: false,
      lastTime: 0,
      isMove: false,
      clearTimer: null,
      panoId: null,
      sceneId: 0,
      socketKey: '',
      isWebsock: false,
      socketRoomNum: 0,
      actions: {
        key: '',
        msgtype: 0,
        count: 0,
        iscreate: true,
        ismaster: true,
        hlookat: 0,
        vlookat: 0,
        sceneid: 0,
      },
      isOnce: true,
    }
  },

  destroyed() {
    this.websocketclose() // 离开路由之后断开websocket连接
  },
  mounted() {
    this.panoId = this.$route.params.panoId
    this.sceneId = this.$route.query.scene_id || 0
    // if (this.$route.path.indexOf('panoview') != -1) {
    //   console.log('2--------------000000000000')
    //   this.init(this.$route.query.scene_id || 0)
    // }
  },
  computed: {
    ...mapGetters([
      'panoInfo',
      'hotspots',
    ]),
  },
  watch: {
    panoInfo: {
      handler(data) {
        if (data) {
          if (!this.isOnce) return
          if (data.templatetype == 11 && data.scene_aerial_list && data.scene_aerial_list.length > 0) {
            console.log('5------------------')
            if (this.$route.query.scene_id) {
              this.init(this.$route.query.scene_id)
              this.isOnce = false
              return
            }
            let filterId = data.scene_aerial_list.filter(item => item.is_aerial)
            // console.log(filterId)
            if (filterId.length > 0) {
              console.log('1------------------000000')
              if (this.isOnce) {
                this.init(filterId[0].scene_id)
                this.isOnce = false
              }
            }
          } else {
            console.log('6---------------')
            this.init(this.$route.query.scene_id || 0)
            this.isOnce = false
          }
        }
        
      },
      immediate: true,
    },
  },
  methods: {
    // 初始化
    init(id) {
      this.$nextTick(() => {
        // init krpano
        this.initEmbedPano(id)

        this.initHammer()

        // socket事件
        this.emitSocketCreate()
        this.emitSocketJoin()
        this.emitSocketScene()
        this.emitSocketClose()
        // ishideall=1时隐藏页面控件
        if (window.location.hash.indexOf('ishideall=1') !== -1) {
          // 公用VR模式的隐藏元素
          this.$vgo.emit('vr:show', false)
          this.handleClearAutoSwitchScene()
        }
      })
    },
    // 创建socket
    emitSocketCreate() {
      this.$vgo.on('socket:create', () => {
        this.actions.msgtype = 0
        setTimeout(() => {
          this.initSocketKey()
          this.initWebSocket()
        }, 20)
      })
    },

    // 加入socket
    emitSocketJoin() {
      this.$vgo.on('socket:join', key => {
        this.socketKey = key
        this.actions.msgtype = 1
        this.actions.key = key
        this.initWebSocket()
      })
    },

    // socket切换场景
    emitSocketScene() {
      this.$vgo.on('socket:scene', id => {
        if (!this.$route.query.isocket) return

        const { vlookat, hlookat } = this.$krp.getView()
        this.actions = { ...this.actions, iscreate: false, sceneid: id }
        this.websocketsend(this.actions)
      })
    },

    // 关闭socket
    emitSocketClose() {
      this.$vgo.on('socket:close', () => {
        this.actions.msgtype = 2
        this.websocketclose()
      })
    },

    // 初始化房间数据
    initSocketKey() {
      if (this.$route.query.isocket) {
        const socketKey = Math.random()
          .toString(36)
          .substr(2, 7)
        this.isWebsock = true
        this.socketKey = socketKey
        this.actions.key = socketKey
        this.$store.commit('SET_SOCKET', true)
        this.$store.commit('SET_SOCKET_ROOM', socketKey)
      }
    },

    // 初始化socket
    initWebSocket() {
      this.websock = new WebSocket(CONFIG.socketUrl)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },

    // 连接建立之后执行send方法发送数据
    websocketonopen() {
      const ismaster = this.$route.query.isocket ? true : false
      this.actions.ismaster = ismaster
      this.websocketsend(this.actions)
    },

    // socket错误后重连
    websocketonerror() {
      this.initWebSocket()
    },

    // 接收到socket数据
    websocketonmessage(e) {
      const data = JSON.parse(e.data)
      if (!this.$route.query.isocket) {
        const { sceneid, vlookat, hlookat } = data
        // 如果有sceneid, 说明是切换场景, 否则是拖动场景
        if (sceneid) {
          this.$krp.switchEffect(sceneid)
          this.$vgo.tip('切换场景')
        } else {
          this.$krp.moveViewCenter(vlookat, hlookat)
        }
      }
      this.$vgo.emit('broadcast:room-num', data.count)
      this.socketRoomNum = data.count
    },

    // 发送数据
    websocketsend(data) {
      this.websock.send(JSON.stringify(data))
    },

    // 关闭
    websocketclose() {
      this.isWebsock = false
      // this.$vgo.emit('broadcast:room-num', this.socketRoomNum)
      if (this.websock) {
        this.websock.close()
      } else {
        this.websock = new WebSocket(CONFIG.socketUrl)
        this.websock.close()
      }
    },

    initHammer() {
      // Get a reference to an element
      const square = document.querySelector('#pano')

      // Create a manager to manager the element
      const manager = new Hammer.Manager(square)

      // Create a recognizer
      const Press = new Hammer.Press({
        time: 500,
      })

      const DoubleTap = new Hammer.Tap({
        event: 'doubletap',
        taps: 2,
      })

      // Add the recognizer to the manager
      manager.add(Press)
      manager.add(DoubleTap)

      // Subscribe to desired event
      manager.on('press', e => {
        if (this.isHideAll) return
        this.handleClearAutoSwitchScene()
        handleScreenShotsDown(e)
      })
      manager.on('doubletap', e => {
       this.handleDbClick()
      })
    },
    handleDbClick() {
      if ($globalconfig.hideHotspot) {
        // 显示隐藏热点
        for (let i in this.hotspots) {
          let hots = this.hotspots[i].hotspotlist
          hots.map(item => {
            this.$krp._krpano.set(`hotspot[hotspot_${item.hot_id}].visible`, !!this.$_isClear)
          })
        }
      }
      this.$_isClear = !this.$_isClear
      
      // ishideall=1时隐藏页面控件
      if (window.location.hash.indexOf('ishideall=1') === -1) {
        this.hideAll()
        this.handleClearAutoSwitchScene()
      }
    },
    // 初始化krpano
    initEmbedPano(sceneid) {
      embedpano({
        swf: $globalconfig.URLS.API + 'krpano/krpano.swf',
        xml: $globalconfig.URLS.API + 'krpano/data/newxml.aspx?pano_id=' + this.panoId + '&r=view&scene_id=' + sceneid,
        target: 'pano',
        html5: 'only',
        mobilescale: 1.0,
        webglsettings: { preserveDrawingBuffer: true },
        passQueryParameters: true,
        onready: this.krpanoReady,
        onerror: this.krpanoError,
      })
    },

    krpanoReady() {
      this.$krp.initKrpno(document.getElementById('krpanoSWFObject'))
    },

    krpanoError(err) {},

    handleDown(e) {
      this.isMove = true
    },

    handleMove(e) {
      if (!this.isMove) return
      handleScreenShotsMove(e)
      this.$vgo.emit('socket:rotate')
      // 同屏事件, 如果是控制方才执行
      if (this.$route.query.isocket && this.isWebsock) {
        const updateLookView = () => {
          const { vlookat, hlookat } = this.$krp.getView()
          this.actions = {
            ...this.actions,
            key: this.socketKey,
            iscreate: false,
            ismaster: true,
            vlookat,
            hlookat,
            sceneid: 0,
          }
          this.websocketsend(this.actions)
        }
        updateLookView()
      }
    },

    handelUp(e) {
      this.lastTime = Date.now()
      this.handleRestartAutoSwitchScene()
      handleScreenShotsEnd(e)
      this.isMove = false
    },

    hideAll() {
      // 公用VR模式的隐藏元素
      if (this.isHideAll) {
        // console.log('1-------')
        this.$vgo.emit('vr:hide', false)
      } else {
        // console.log('2-------')
        this.$vgo.emit('vr:show', false)
      }
      this.isHideAll = !this.isHideAll
    },
  },
}
</script>

<style lang="stylus">
#pano
  width 100%
  height 100%
</style>
